package com.itheima.web.exception;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.HashMap;
import java.util.Map;

//全局异常处理器，@ControllerAdvice配合ExceptionHandler使用
//支持两种异常，一种是自定义异常，一种是普通异常，exceptionHandler注解用来捕获那种异常
@ControllerAdvice
public class GlobalExceptionAdvice {
    //处理自定义的异常
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity handlerBusinessException(Exception e){
        //打印异常
        e.printStackTrace();

        //返回给浏览器异常
        Map<String, String> map = new HashMap<>();
        map.put("message", e.getMessage());
        return ResponseEntity.status(500).body(map);
    }

    //处理普通异常
    @ExceptionHandler(Exception.class)
    public ResponseEntity handlerException(Exception e){
        //打印异常
        e.printStackTrace();

        //返回错误
        Map<String, String> map = new HashMap<>();
        map.put("message", e.getMessage());
        return ResponseEntity.status(500).body(map);
    }


}
